package com.well.kernel.mybatis.generator;

import org.apache.log4j.Logger;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.GeneratedXmlFile;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Copyright &copy; Well All rights reserved.
 * Author:Well
 * Date:2016/12/27
 * Description:mybatis 代码生成器的启动类
 *      只生成 entity、mapper、xml ,该类已经弃用，推荐使用 com.well.kernel.mybatis.generator.CodeGenerator 代码生成器
 */

@Deprecated
public class Generator
{
    private static Logger logger=Logger.getLogger(Generator.class);

    public static void main(String[] args) {
        /* 通过纯 Java 方式生成代码 */
        Generator generator=new Generator();
        generator.generate();

        /* 通过配置文件方式生成代码，该方法已经弃用 */
        /*String configFile="mybatis/mybatis-generator.xml";
        Generator g=new Generator();
        g.generator(configFile);*/

    }

    /**
     * 纯 Java 方式生成代码
     */
    public void generate(){
        try{
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true; // 覆盖已有文件
            Configuration configuration = new Configuration(); // 代码生成器的配置

            /* 代码生成器的上下文环境 */
            Context context=new Context(ModelType.FLAT);
            context.setId("context");
            context.setTargetRuntime("MyBatis3Simple");
            context.addProperty("javaFileEncoding","UTF-8");
            context.addProperty("useMapperCommentGenerator","false");

            /* mybatis mapper 的插件配置 */
            PluginConfiguration mapperPluginConfiguration=new PluginConfiguration();
            mapperPluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
            mapperPluginConfiguration.addProperty("mappers", "com.well.kernel.mybatis.mapper.ABaseMapper");
            mapperPluginConfiguration.addProperty("caseSensitive", "true");
            mapperPluginConfiguration.addProperty("forceAnnotation", "true");
//            mapperPluginConfiguration.addProperty("beginningDelimiter", "`");
//            mapperPluginConfiguration.addProperty("endingDelimiter", "`");
            context.addPluginConfiguration(mapperPluginConfiguration);

            /* 注释生成器配置 */
            CommentGeneratorConfiguration commentGeneratorConfiguration=new CommentGeneratorConfiguration();
            commentGeneratorConfiguration.setConfigurationType("com.well.kernel.mybatis.generator.CommentGenerator");
            context.setCommentGeneratorConfiguration(commentGeneratorConfiguration);

            /* JDBC 连接配置 */
            JDBCConnectionConfiguration jdbcConnectionConfiguration=new JDBCConnectionConfiguration();
            jdbcConnectionConfiguration.setDriverClass("com.mysql.jdbc.Driver");
            jdbcConnectionConfiguration.setConnectionURL("jdbc:MySQL://127.0.0.1:3306/jeewell");
            jdbcConnectionConfiguration.setUserId("root");
            jdbcConnectionConfiguration.setPassword("root");
            context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration);

            /* 生成 entity 类的配置 */
            JavaModelGeneratorConfiguration javaModelGeneratorConfiguration=new JavaModelGeneratorConfiguration();
            javaModelGeneratorConfiguration.setTargetProject("src/main/java");
            javaModelGeneratorConfiguration.setTargetPackage("com.well.module.user.entity");
            javaModelGeneratorConfiguration.addProperty("rootClass","com.well.kernel.mybatis.persistence.ABaseEntity");
            context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration);

            /* 生成 xml 文件的配置 */
            SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration=new SqlMapGeneratorConfiguration();
            sqlMapGeneratorConfiguration.setTargetProject("src/main/java");
            sqlMapGeneratorConfiguration.setTargetPackage("com.well.module.user.mapper");
            context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration);

            /* 生成 mapper 接口的配置 */
            JavaClientGeneratorConfiguration javaClientGeneratorConfiguration=new JavaClientGeneratorConfiguration();
            javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
            javaClientGeneratorConfiguration.setTargetProject("src/main/java");
            javaClientGeneratorConfiguration.setTargetPackage("com.well.module.user.mapper");
            context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration);

            /* 添加表名称 */
            TableConfiguration tableConfiguration=new TableConfiguration(context);
            tableConfiguration.setTableName("user_info");
//            tableConfiguration.setDomainObjectName("UserInfo");
            context.addTableConfiguration(tableConfiguration);

            /* 输出代码生成器上下文环境的内容，已经格式化 */
//            String xml=context.toXmlElement().getFormattedContent(1);
//            System.out.println(xml);

            /* 添加代码生成器的上下文环境 */
            configuration.addContext(context);

            /* 生成代码 */
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(configuration, callback, warnings);
            myBatisGenerator.generate(null);
            /* 打印结果 */
            this.printResult(myBatisGenerator, warnings);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 配置文件方式生成代码，该方法已经弃用
     * @param configFile 配置文件
     */
    @Deprecated
    public void generate(String configFile){
        try{
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            ConfigurationParser cp = new ConfigurationParser(warnings);
            InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream(configFile);
            Configuration config = cp.parseConfiguration(is);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
            this.printResult(myBatisGenerator, warnings);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 输出生成结果
     * @param myBatisGenerator
     * @param warnings
     */
    private void printResult(MyBatisGenerator myBatisGenerator,List<String> warnings){
        List<GeneratedJavaFile> generatedJavaFileList=myBatisGenerator.getGeneratedJavaFiles();
        Iterator<GeneratedJavaFile> iteratorJava=generatedJavaFileList.iterator();
        GeneratedJavaFile generatedJavaFile=null;
        System.out.println("生成的 Java 类：");
        while(iteratorJava.hasNext()){
            generatedJavaFile=iteratorJava.next();
            System.out.println(generatedJavaFile.getFileName());
        }
        List<GeneratedXmlFile> generatedXmlFileList=myBatisGenerator.getGeneratedXmlFiles();
        Iterator<GeneratedXmlFile> iteratorXml=generatedXmlFileList.iterator();
        GeneratedXmlFile generatedXmlFile=null;
        System.out.println("生成的 xml 文件：");
        while(iteratorXml.hasNext()){
            generatedXmlFile=iteratorXml.next();
            System.out.println(generatedXmlFile.getFileName());
        }
        if(warnings.size()!=0){
            System.out.println("警告：");
            for(String warning:warnings){
                System.out.println(warning);
            }
        }
        System.out.println("生成文件成功！");
    }

}
